using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.IO;
using System.Text;
using System.Web.UI.WebControls;
using System.Xml.Serialization;
using AdHocReports.Properties;
using System.Text.RegularExpressions;
using System.Data.OleDb;
using System.Data;

namespace AdHocReports
{
    public partial class step2 : BasePage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            MasterPage.NextEnabled = true;
            MasterPage.BackEnabled = true;
            MasterPage.CancelEnabled = true;
            MasterPage.NextClicked += new EventHandler(mp_NextClicked);
            MasterPage.BackClicked += new EventHandler(mp_BackClicked);
            MasterPage.CancelClicked += new EventHandler(mp_CancelClicked);
            MasterPage.ContentTitle = "Manage a Report: Create, Run, or Delete";

            if (!IsPostBack && !IsCallback)
            {
                BindData();
            }
        }

        private void BindData()
        {
            cboViews.Items.Clear();
            cboReports1.Items.Clear();
            cboReports2.Items.Clear();

            // Establish a new connection
            using (OleDbConnection oleConn = new OleDbConnection(ReportDefinition.ConnectionString))
            {
                // Open the connection
                oleConn.Open();

                // Create a data table with the views from the connection
                using (DataTable oleTable = oleConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new Object[] { null, null, null, "VIEW" }))
                {
                    // Loop through view names returned
                    for (int i = 0; i < oleTable.Rows.Count; i++)
                    {
                        if (Regex.IsMatch(oleTable.Rows[i].ItemArray[2].ToString(), Settings.Default.SourceViews))
                        {
                            // Create a new list item
                            ListItem li = new ListItem(oleTable.Rows[i].ItemArray[2].ToString(), oleTable.Rows[i].ItemArray[2].ToString());
                            // Add the view name to the combo list
                            cboViews.Items.Add(li);
                        }
                    }
                }

                // Close the connection
                oleConn.Close();
            }

            using (SqlConnection conn = new SqlConnection(Settings.Default.SavedReports))
            {
                conn.Open();
                using (SqlCommand comm = new SqlCommand())
                {
                    comm.Connection = conn;
                    comm.CommandText = "SELECT ReportID, ReportName FROM Reports ORDER BY ReportName";
                    SqlDataReader reader = comm.ExecuteReader();
                    while (reader.Read() == true)
                    {
                        ListItem li = new ListItem(reader.GetString(1), reader.GetInt32(0).ToString());
                        cboReports1.Items.Add(li);
                        cboReports2.Items.Add(li);
                    }
                }
                conn.Close();
            }
        }

        void mp_CancelClicked(object sender, EventArgs e)
        {
            Response.Redirect("~/");
        }

        void mp_BackClicked(object sender, EventArgs e)
        {
            Response.Redirect("~/");
        }

        void mp_NextClicked(object sender, EventArgs e)
        {
            if (rblType.Items[0].Selected == true)
            {
                ContinueNew();
            }
            else if (rblType.Items[1].Selected == true)
            {
                ContinueExisting();
            }
            else if (rblType.Items[2].Selected == true)
            {
                DeleteExisting();
            }
        }

        private void DeleteExisting()
        {
            // If a saved report has been selected
            if ((cboReports2.Items.Count > 0) && (cboReports2.SelectedIndex >= 0))
            {
                using (SqlConnection conn = new SqlConnection(Settings.Default.SavedReports))
                {
                    conn.Open();
                    using (SqlCommand comm = new SqlCommand())
                    {
                        comm.Connection = conn;
                        comm.CommandText = "DELETE FROM Reports WHERE ReportID = @reportId";
                        comm.Parameters.Add(new SqlParameter("reportId", Convert.ToInt32(cboReports2.SelectedValue)));
                        comm.ExecuteNonQuery();
                    }
                    conn.Close();
                }

                BindData();
            }
        }

        private void ContinueNew()
        {
            // If a view has been selected
            if ((cboViews.Items.Count > 0) && (cboViews.SelectedIndex >= 0))
            {
                ReportDefinition.View = cboViews.Text;
                // Move on to the next page
                Response.Redirect("step3.aspx");
            }
        }

        private void ContinueExisting()
        {
            // If a saved report has been selected
            if ((cboReports1.Items.Count > 0) && (cboReports1.SelectedIndex >= 0))
            {
                using (SqlConnection conn = new SqlConnection(Settings.Default.SavedReports))
                {
                    conn.Open();
                    using (SqlCommand comm = new SqlCommand())
                    {
                        comm.Connection = conn;
                        comm.CommandText = "SELECT ReportDefinition FROM Reports WHERE ReportID = @reportId";
                        comm.Parameters.Add(new SqlParameter("reportId", Convert.ToInt32(cboReports1.SelectedValue)));
                        SqlDataReader reader = comm.ExecuteReader();
                        if (reader.Read() == true)
                        {
                            XmlSerializer xml = new XmlSerializer(typeof(ReportDefinition));
                            MemoryStream ms = new MemoryStream();
                            SqlXml sqlXml = reader.GetSqlXml(0);
                            ms.Write(ASCIIEncoding.ASCII.GetBytes(sqlXml.Value), 0, sqlXml.Value.Length);
                            ms.Seek(0, SeekOrigin.Begin);
                            ReportDefinition.Current = (ReportDefinition)xml.Deserialize(ms);
                        }
                    }
                    conn.Close();
                }

                // Transfer the report viewing page
                Response.Redirect("showReport.aspx");
            }
        }
    }
}